package com.njlime.cms.controller.sys;

import com.njlime.cms.entities.Information;
import com.njlime.cms.service.sys.InformationService;
import com.njlime.cms.util.UrlUtil;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.BusinessException;
import com.njlime.core.exception.ExceptionState;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.UnitService;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * Created by Dean on 2017/10/14.
 * 微信发布
 */
@Controller
@RequestMapping(value = "wechat")
public class WeChatPublishController extends BaseController {
    @Resource
    private InformationService informationService;
    @Resource
    private UnitService unitService;

    public static WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
    public static WxMpService wxService;
    public static WxMpMaterialService wxMpMaterialService;

    private void initWxMp() throws Exception{
        Unit rootUnit = getLoginUser().getRootUnit();
        if(rootUnit != null){
            UnitWxConfig wxConfig = unitService.getWxConfig(rootUnit.getId());
            if(wxConfig != null){
                if(config.getAppId() == null || config.getAppId().equals(wxConfig.getApp_id())){
                    config.setAppId(wxConfig.getApp_id());
                    config.setSecret(wxConfig.getApp_secret()); // 设置微信公众号的app corpSecret*/
                    //config.setToken("fdgsfsgfdsgfdsgergergregre"); // 设置微信公众号的token
                    //config.setAesKey("la4Mdz5TAgKmb0Qj42RFAItWDZ3OQDlwUnxQu5ziA2p"); // 设置微信公众号的EncodingAESKey

                    wxService = new WxMpServiceImpl();
                    wxService.setWxMpConfigStorage(config);
                    wxMpMaterialService = new WxMpMaterialServiceImpl(wxService);
                }
            }else{
                throw new BusinessException("请先设置微信信息");
            }
        }else{
            throw new BusinessException("平台用户无法操作");
        }

    }

    /**
     * 保存到微信
     *
     * @return
     */
    @RequestMapping(value = "informationSTWX")
    @ResponseBody
    public String informationSTWX(int id,HttpServletRequest request) {
        Information information = informationService.findOne(id);
        try {
            initWxMp();
            WxMpMaterial wxMaterial = new WxMpMaterial();
            File file = UrlUtil.url2File(information.getTheme_img1(),"theme_" + id + ".jpg",request.getServletContext().getRealPath("/"));
            wxMaterial.setFile(file);
            wxMaterial.setName(information.getTitle());
            WxMpMaterialUploadResult res = wxService.getMaterialService().materialFileUpload("image", wxMaterial);

            WxMpMaterialNews wxMpMaterialNewsSingle = new WxMpMaterialNews();
            WxMpMaterialNews.WxMpMaterialNewsArticle mpMaterialNewsArticleSingle =
                    new WxMpMaterialNews.WxMpMaterialNewsArticle();
            mpMaterialNewsArticleSingle.setAuthor(" ");
            mpMaterialNewsArticleSingle.setThumbMediaId(res.getMediaId());
            mpMaterialNewsArticleSingle.setTitle(information.getTitle());
            mpMaterialNewsArticleSingle.setContent(information.getContent());
            mpMaterialNewsArticleSingle.setContentSourceUrl(information.getSource_url());
            mpMaterialNewsArticleSingle.setShowCoverPic(true);
            mpMaterialNewsArticleSingle.setDigest(information.getAbstract_info());
            wxMpMaterialNewsSingle.addArticle(mpMaterialNewsArticleSingle);
            WxMpMaterialUploadResult resSingle =
                    wxService.getMaterialService().materialNewsUpload(wxMpMaterialNewsSingle);
            System.out.println("success");
            file.delete();
            return toJsonSuccessData(resSingle);
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,e.getMessage());
        }
    }


    @RequestMapping(value = "getWxConfig")
    @ResponseBody
    public String getWxConfig(HttpServletRequest request, HttpServletResponse response) {
        Unit rootUnit = getLoginUser().getRootUnit();
        if(rootUnit != null){
            UnitWxConfig wxConfig = unitService.getWxConfig(rootUnit.getId());
            if(wxConfig != null){
                return toJsonSuccessData(rootUnit.getUnit_name());
            }else{
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"请先设置微信信息");
            }
        }else{
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"平台用户无法操作");
        }
    }

}
